<?php

namespace Our;

use Zend\Session\Container;

/**
 * admin模块控制器抽象类
 *
 * @package Our
 * @author chenjiebin <303410541@qq.com>
 */
abstract class Controller_AbstractAdmin extends Controller_Abstract
{
    /**
     * admin控制器初始化方法，通常可以在这里校验是否登录或者授权
     */
    public function init()
    {
        $moduleName = strtolower($this->getRequest()->getModuleName());
        $controllerName = strtolower($this->getRequest()->getControllerName());
        if (($moduleName == 'admin') &&
            in_array($controllerName, array('login'))
        ) {
            return true;
        }

        $AdminModel = \Admin\AdminModel::getInstance();
        $admin = $AdminModel->validateLogin();
        if (!$admin) {
            $this->redirect($AdminModel::$_loginUrl);
            exit();
        }
        if (!$AdminModel->checkStatus($admin["admin_id"])) {
            $container = new Container('admin');
            $container->admin = null;
            $this->redirect($AdminModel::$_loginUrl);
            exit();
        }
        return true;
    }

    /**
     * 往视图层传递成功的消息
     *
     * @param string $message
     * @param array $data
     */
    protected function _assignSuccessMessage($message = "保存成功", $data = array())
    {
        $result = array(
            'status' => 0,
            'message' => $message,
            'data' => $data,
        );
        $this->getView()->assign("result", $result);
    }

    /**
     * 往视图层传递失败的消息
     *
     * @param string $message
     * @param int $status
     * @param array $data
     */
    protected function _assignErrorMessage($message = "保存失败", $status = 1, $data = array())
    {
        $result = array(
            'status' => $status,
            'message' => $message,
            'data' => $data,
        );
        $this->getView()->assign("result", $result);
    }

    /**
     * 获取搜索语句条件转换成sql的where条件，暂时都用=
     *
     * @param array $options 参数
     * @return array
     */
    protected function _getWhere($options = array())
    {
        if (!$this->_getParam('where')) {
            return array();
        }
        //解析获取的where参数字符串
        $params = $this->_analyseWhere();

        $where = array();
        foreach ($params as $key => $value) {
            //如果有设置like字段
            if (!empty($options["like"]) && in_array($key, $options["like"])) {
                $where['`' . $key . '` like ?'] = '%' . rawurldecode($value) . '%';
                continue;
            }
            $where['`' . $key . '` = ?'] = $value;
        }

        return $where;
    }

    /**
     * 分析where
     *
     * @return array
     */
    protected function _analyseWhere()
    {
        $params = array();
        $where = $this->_getParam('where', null);
        if ($where === null) {
            return $params;
        }
        $where = rawurldecode($where);
        $whereParams = explode('__iceup__', $where);
        $total = count($whereParams);
        for ($i = 0; $i < $total; $i += 2) {
            $params[$whereParams[$i]] = $whereParams[$i + 1];
        }
        return $params;
    }

    /**
     * 获取排序条件
     *
     * @param array $default 默认排序
     * @return array
     */
    protected function _getOrder($default = array())
    {
        $order = $this->_getParam('order_by', array());
        if (!$order) {
            return $default;
        }

        return array(rawurldecode($order));
    }

    /**
     * 获取搜索时的翻页的url
     *
     * @return string
     */
    protected function _getBaseUrl()
    {
        $actionUrl = '';

        $i = 1;
        $requests = array_filter(explode("/", $_SERVER['REQUEST_URI']));
        foreach ($requests as $v) {
            $actionUrl .= '/' . $v;
            $i++;
            if ($i > 3) {
                break;
            }
        }
        $actionUrl .= '/';

        $params = $this->_getParam();
        foreach ($params as $key => $value) {
            if ($key != 'page') {
                $actionUrl .= $key . '/' . rawurldecode($value) . '/';
            }
        }

        $actionUrl .= 'page/';
        return $actionUrl;
    }

    // 下面是通用的上传方法
    protected function _upload()
    {
        $imageSize = 20000;
        //上传到本地服务器
        $uploadConfig = new \Our\Upload\Config(array(
                'dir' => '/upload/tmp',
                'fileName' => 'upload_image_file',
                'saveFilename' => md5(time() . rand(10000, 99999)),
                'size' => $imageSize * 1024)
        );
        $upload = new \Our\Upload\Main($uploadConfig);
        $result = $upload->upload();

        $imageFile = rtrim($result[1], '/') . '/' . $result[2]; //本地服务器保存的图片，存在放/public/image目录下

        //上传到云服务器
        $cloudMethod = '_' . \Bootstrap::getConfig("upload.cloud.type") . "Upload";
        $uploadCloudResult = $this->$cloudMethod($imageFile);

        $imageSize = getimagesize($imageFile);
        $data = array(
            'width' => $imageSize[0],
            'height' => $imageSize[1],
            'dest_file_name' => \Bootstrap::getConfig("upload.pic.url") . $uploadCloudResult['file_relative_url'],
            'status' => 1,
        );

        //上传到云服务器后，删除本地文件
        if (file_exists($imageFile)) {
            unlink($imageFile);
        }
        return $data;
    }

    /**
     * 上传到本地服务器
     * @param $originFile
     * @return array
     */
    public function _localhostUpload($originFile)
    {
        $tmp = explode(".", $originFile);
        $dir = APPLICATION_PATH . "/public/upload" . date('/Y/m/d/');
        if (!file_exists($dir)) {
            mkdir($dir, 0777, true);
        }
        $key = md5_file($originFile) . "." . $tmp[count($tmp) - 1];
        copy($originFile, $dir . $key);
        $result = [
            "file_relative_url" => "upload" . date('/Y/m/d/') . $key,
        ];
        return $result;
    }

    /**
     * 上传文件到七牛云
     * @param $originFile
     * @return array
     * @throws \Exception
     */
    protected function _qiniuUpload($originFile)
    {
        require_once APPLICATION_PATH . '/application/library/Qiniu/functions.php';

        $accessKey = \Bootstrap::getConfig("qiniu.ak");
        $secretKey = \Bootstrap::getConfig("qiniu.sk");
        $auth = new \Qiniu\Auth($accessKey, $secretKey);

        $bucket = \Bootstrap::getConfig("qiniu.bucket");
        $token = $auth->uploadToken($bucket);
        $uploadMgr = new \Qiniu\Storage\UploadManager();

        $key = $this->_calcQiniuUploadKey($originFile);
        list($res, $err) = $uploadMgr->putFile($token, $key, $originFile);
        if ($err !== null) {
            \Error\ErrorModel::throwException(100002, "七牛上传错误：" . $err->message());
        }

        $imageInfo = getimagesize($originFile);

        $result = array(
            "file_relative_url" => $res['key'] . "?width=" . $imageInfo[0] . "&height=" . $imageInfo[1],
        );
        return $result;
    }

    /**
     * 计算七牛上传需要的key
     *
     * @param string $originFile
     * @return string
     */
    protected function _calcQiniuUploadKey($originFile)
    {
        $tmp = explode(".", $originFile);
        $key = date('/Y/m/d/') . md5_file($originFile) . "." . $tmp[count($tmp) - 1];
        return $key;
    }
}
